﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using LEMMATIZERLib;

namespace OffLineFilter
{
    public class FileNormalizer
    {
        public string FileName { get; set; }
        public string[] Words { get; set; }

        protected string morphoAnalyzer { get { return "mystem.exe"; } }
        protected string outFileName { get { return FileName + ".tmp"; } }
        protected string morphoAnalyzerArgs { get { return String.Format("-nl \"{0}\" \"{1}\"", FileName, outFileName); } }

        public FileNormalizer(String fileName)
        {
            FileName = fileName;
        }

        private bool MorphoAnalyzerExecute()
        {
            ProcessStartInfo pinfo = new ProcessStartInfo(morphoAnalyzer);
            pinfo.CreateNoWindow = true;
            pinfo.UseShellExecute = false;
            pinfo.Arguments = morphoAnalyzerArgs;
            pinfo.WindowStyle = ProcessWindowStyle.Hidden;
            try
            {
                Process process = Process.Start(pinfo);
                process.WaitForExit();
            }
            catch
            {
                return false;
            }

            return true;
        }

        private string[] ReadWords()
        {
            List<String> words = new List<string>();
            try
            {
                using (StreamReader stream = new StreamReader(outFileName, Encoding.Default))
                {
                    String line;
                    while ((line = stream.ReadLine()) != null)
                    {
                        String[] forms = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        if (forms.Length > 0)
                            line = forms[0];

                        words.Add(line);
                    }
                }
            }
            catch
            {
                return null;
            }
            return words.ToArray();
        }

        private bool Cleanup()
        {
            try
            {
                if (File.Exists(outFileName))
                    File.Delete(outFileName);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public string[] Normalize()
        {
            if (!MorphoAnalyzerExecute())
                return null;

            Words = ReadWords();
            Cleanup();

            return Words;
        }
    }
}
